﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Light.Framework.Castle;
using Light.Weixin.Model;
using Light.Weixin.Contract;
using Light.Utility;

namespace Light.Weixin
{
    /// <summary>
    /// 微信平台应用工具类
    /// </summary>
    public class WxAppHelper
    {
        /// <summary>
        /// 向管理员账号发送“系统提醒”消息（要设置 Key=warning的消息模板）
        /// </summary>
        /// <param name="firstword">首句</param>
        /// <param name="content">提醒内容</param>
        /// <param name="operater">操作人</param>
        /// <param name="timeOperate">操作时间</param>
        public static OperateResult SendWarningMsgToAdmins(string firstword, string content, string operater, DateTime timeOperate)
        {
            OperateResult result = new OperateResult();
            try
            {
                WxApp app = GetDefaultWxApp();
                WxMsgTpl tpl = app.GetMsgTpl("warning");
                WxTplMsg msg = new WxTplMsg();
                msg.FirstWords = firstword;
                msg.Body.Add("keyword1", DateTime.Now);
                msg.Body.Add("keyword2", content);
                msg.Body.Add("keyword3", operater);
                msg.Body.Add("keyword4", WebHelper.GetCurrentRequestIP());
                msg.Body.Add("keyword5", timeOperate);
                msg.Remark = "登录系统查看详情";
                msg.DetailUrl = "http://wyzf.com.cn";

                string[] openids = app.AdminOpenIDs.Split(',');
                foreach (var openid in openids)
                {
                    msg.ToUserOpenID = openid;
                    result = app.SendTplMsg(msg, tpl);
                }
            }
            catch (Exception ex)
            {
                ServerApplication.Logger.LogError("向管理员发送微信消息失败，" + ex.Message);
                result.IsSucced = false;
                result.Message = ex.Message;
            }

            return result;

        }

        /// <summary>
        /// 用默认的微信公众号向管理员发送消息
        /// </summary>
        /// <typeparam name="T">消息内容来源类型</typeparam>
        /// <param name="msg">消息</param>
        /// <param name="tpl">模板</param>
        /// <param name="objContent">消息内容来源对象</param>
        public static void SendTplMsgToAdmins<T>(WxTplMsg msg, WxMsgTpl tpl, T objContent)
        {
            OperateResult result = new OperateResult();
            try
            {
                WxApp app = GetDefaultWxApp();
                string[] openids = app.AdminOpenIDs.Split(',');
                foreach (var openid in openids)
                {
                    msg.ToUserOpenID = openid;
                    result = app.SendTplMsg<T>(msg, tpl, objContent);
                }
            }
            catch (Exception ex)
            {
                ServerApplication.Logger.LogError("向管理员发送客服消息失败，" + ex.Message);
                result.IsSucced = true;
                result.Message = ex.Message;
            }
        }

        /// <summary>
        /// 向管理员发送客服文本消息
        /// </summary>
        /// <param name="msg"></param>
        public static OperateResult SendCusMsgToAdmins(WxMsg msg)
        {
            OperateResult result = new OperateResult();
            try
            {
                WxApp app = GetDefaultWxApp();
                //WxMsg msg = new WxMsg(WxMsgType.Text);
                //msg.Content = text;

                string[] openids = app.AdminOpenIDs.Split(',');
                foreach (var openid in openids)
                {
                    msg.ToUserName = openid;
                    result = app.SendCusMsg(msg);
                }
            }
            catch (Exception ex)
            {
                ServerApplication.Logger.LogError("向管理员发送客服消息失败，" + ex.Message);
                result.IsSucced = false;
                result.Message = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 获取基础操作的token
        /// </summary>
        /// <param name="latest">获取最新token</param>
        /// <returns></returns>
        public static string GetBasicToken(bool latest)
        {
            WxApp wxApp = GetDefaultWxApp();
            Light.Utility.OAuth.OAuthConfig config = new Light.Utility.OAuth.OAuthConfig()
            {
                AppId = wxApp.AppID,
                AppKey = wxApp.AppSecret
            };
            return Light.Utility.OAuth.WeixinHelper.GetBasicToken(config, latest);
        }

        /// <summary>
        /// 获取默认的微信公众号
        /// </summary>
        /// <returns></returns>
        public static WxApp GetDefaultWxApp()
        {
            WxApp app = ServerApplication.ComponentFactory.Create<IWxAppComponent>().Get(WxAppType.Weixin);

            if (app == null)
            {
                throw new Exception("请先添加默认微信公众号");
            }
            if (String.IsNullOrEmpty(app.AdminOpenIDs))
            {
                throw new Exception("请先设置公众号管理员OpendIDs");
            }
            return app;
        }

        /// <summary>
        /// 获取临时类型的带参数二维码图片
        /// </summary>
        /// <param name="scenceId">参数</param>
        /// <param name="fileName">二维码图片路径</param>
        /// <returns></returns>
        public static string GetQrCodeTemp(int scenceId, string fileName)
        {
            WxApp app = GetDefaultWxApp();
            using (System.Drawing.Image image = app.GetQRCode(QrCodeType.Temp, scenceId))
            {
                image.Save(fileName);
            }
            return fileName;
        }

        /// <summary>
        /// 长链接变短链接
        /// </summary>
        /// <param name="longUrl">http://或https://开头的链接</param>
        /// <returns></returns>
        public static string GetShortUrl(string longUrl)
        {
            WxApp wxApp = GetDefaultWxApp();
            return wxApp.GetShortUrl(longUrl);
        }
    }
}
